package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;

import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author Du leilei
 * @version 1.0
 * @Description
 * @createTime 2023年10月25日 18:11:00
 */
@Service
@Transactional
@Slf4j
public class ApArticleServiceImpl  extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private CacheService cacheService;
    /**
     * 加载首页              type  1
     *
     * @param homeDto
     * @return 加载更新       type  2
     * @return 加载更多       type  1
     */
    @Override
    public ResponseResult load(ArticleHomeDto homeDto, int type) {
        //1. 参数校验
        if (homeDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2. 数据处理
        if (homeDto.getMaxBehotTime() == null){
            homeDto.setMaxBehotTime(new Date(0L));
        }
        if (homeDto.getMinBehotTime() == null){
            homeDto.setMinBehotTime(new Date());
        }
        if (homeDto.getSize() == null || homeDto.getSize() <= 0){
            homeDto.setSize(10);
        }else{
            homeDto.setSize(Math.min(homeDto.getSize(), 50));   //防止分页条数过大，限制每页最大50条
        }

        //3. 调用mapper层处理数据
        List<ApArticle> list = apArticleMapper.loadArticleList(homeDto,type);

        //4. 返回结果
        return ResponseResult.okResult(list);
    }



    /**
     * 在缓存中查询
     * @param homeDto
     * @param loadtypeLoadMore
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult loadIndex(ArticleHomeDto homeDto, Short loadtypeLoadMore) {
        String str = cacheService.get(ArticleConstants.HOT_ARTICLE + homeDto.getTag());
        if (str != null){
            //缓存里有,直接进缓存查
            List<HotArticleVo> list = JSON.parseObject(str, List.class);
            return ResponseResult.okResult(list);
        }else {
            return load(homeDto,loadtypeLoadMore);
        }
    }

}
